#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

//线程的清理
//异常退出的时候清理释放malloc

//处理
void test(void* agr)
{
	printf("agr = %s\n", (char*)agr);
}

//子线程
void* fun(void* agr)
{

	printf("The thread is create\n");
	
	//修改默认,碰到取消点才取消
	//pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL);
	//立即取消
	pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
	pthread_cleanup_push(test,"abcd");

	sleep(1);
	printf("pid = %d tid = %lu\n", getpid(), pthread_self());

	//取消点
	while(1)
	{
		sleep(1);
	}

	pthread_exit("线程结束");

	pthread_cleanup_pop(1);
}


int main()
{
	pthread_t tid;
	int ret;
	void* retv;
	
	//线程创建
	ret =  pthread_create(&tid, NULL, fun, NULL);
	sleep(1);

	//取消线程
	pthread_cancel(tid);

	//线程回收
	pthread_join(tid, &retv);
	//printf("retv =%s\n",(char*)retv);

	while(1)
	{
		sleep(1);
	}
}
